package com.example.demo.utils;

import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.dysmsapi20170525.Client;
import com.example.demo.pojo.properties.AliyunSmsProperties;

import java.util.HashMap;
import java.util.Map;

public class AliyunSmsUtil {

    private static Client createClient(AliyunSmsProperties aliyunSmsProperties) throws Exception {
        Config config = new Config()
                .setAccessKeyId(aliyunSmsProperties.getAccessKeyId())
                .setAccessKeySecret(aliyunSmsProperties.getAccessKeySecret());

        // 配置 Endpoint
        config.endpoint = aliyunSmsProperties.getEndpoint();

        return new Client(config);
    }

    /**
     * 发送短信验证码
     * @param aliyunSmsProperties 阿里云短信服务的各种配置信息类
     * @param phone 目标手机号码
     * @param code 验证码
     * @param templateCode 短信模板
     * @return 请求状态码和状态码的描述的Map
     * @throws Exception
     */
    private static Map<String, String> sendSms(AliyunSmsProperties aliyunSmsProperties, String phone, String code, String templateCode) throws Exception {
        // 初始化请求客户端
        Client client = createClient(aliyunSmsProperties);

        String templateParam = "{\"code\":\"" + code + "\"}";


        // 构造请求对象，请填入请求参数值
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers(phone)
                .setSignName(aliyunSmsProperties.getSignName())
                .setTemplateCode(templateCode)
                .setTemplateParam(templateParam);

        // 获取响应对象
        SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);

        SendSmsResponseBody body = sendSmsResponse.getBody();
        String resultCode = body.getCode();
        String message = body.getMessage();

        Map<String, String> result = new HashMap<>();
        result.put("code", resultCode);
        result.put("message", message);

        return result;
    }

    /**
     * 发送4-6位纯数字短信验证码
     * @param aliyunSmsProperties 阿里云短信服务的各种配置信息类
     * @param phone 目标手机号码
     * @param code 验证码
     * @return 请求状态码和状态码的描述的Map
     * @throws Exception
     */
    public static Map<String, String> sendDigitSms(AliyunSmsProperties aliyunSmsProperties, String phone, String code) throws Exception {
        return sendSms(aliyunSmsProperties, phone, code, aliyunSmsProperties.getTemplateCodeDigit());
    }

    /**
     * 发送4-6位数字+字母组合或仅字母短信验证码
     * @param aliyunSmsProperties 阿里云短信服务的各种配置信息类
     * @param phone 目标手机号码
     * @param code 验证码
     * @return 请求状态码和状态码的描述的Map
     * @throws Exception
     */
    public static Map<String, String> sendLetterSms(AliyunSmsProperties aliyunSmsProperties, String phone, String code) throws Exception {
        return sendSms(aliyunSmsProperties, phone, code, aliyunSmsProperties.getTemplateCodeLetter());
    }
}
